
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>

int main(void)
{
    char buffer[1024];
    int fd1, fd2;
    int ret;

    /*  打开src_file  */
    fd1 = open("./src_file",O_RDONLY);
    if (-1 == fd1  )
    {
        printf("Error: Cannot open src_file!\n");
        return -1;
    }

    /*新建dest_file文件并打开*/
    fd2 = open("./dest_file",O_WRONLY|O_CREAT|O_EXCL,S_IRWXU|S_IRGRP|S_IROTH);
    if (-1 == fd2)
    {
        printf("Error: Cannot open dest_file\n");
        ret = -1;
        goto err1;
    }

    /*将src_file文件读写位置移动到偏移文件头500个字节处*/
    ret = lseek(fd1,500,SEEK_SET);
    if (-1 == ret)
    {
        goto err2;
    }
    
    /*读取src_file文件数据，大小为1KByte*/
    ret = read(fd1,buffer,sizeof(buffer));
    if (-1 == ret)
    {
        printf("read failed\n");
        goto err2;
    }

    /*将dest_file文件读写位置移动到文件头*/
    ret = lseek(fd2,0,SEEK_SET);
    if (-1 == ret)
    {
        goto err2;
    }

    /*将buffer中到数据写入dest_file文件，大小为1KByte*/
    ret = write(fd2,buffer,sizeof(buffer));
    if (-1 == ret)
    {
        printf("write failed!\n");
        goto err2;
    }

    printf("test successful\n");
    ret = 0;

    err2:
        close(fd2);
    
    err1:
        close(fd1);

    return ret;
    
}